<?php

namespace co2_OS;

class run

{
	protected static
		$conf
		;
		
	protected
	  $__head=array()
	  ;
		
	public function
	__construct
	()
	
	{
		$class=get_class($this);
		
		$this->__head=(object)array(
		  'app'         =>  preg_replace('/^co2_OS\\\apps\\\(.+)\\\.+$/U','$1',$class),
		  'channel'     =>  preg_replace('/^co2_OS\\\apps\\\(.+)\\\(.+)\\\.+$/U','$2',$class),
		  'version'     =>  (object)
		    array
		    (
		      'coded'     =>  preg_replace('/^co2_OS\\\apps\\\.+\\\.+\\\(.+)\\\.+$/U','$1',$class),
		      'organic'   =>  preg_replace('/v(\d+)_(\d+)_(\d+)/','$1.$2.$3',preg_replace('/^co2_OS\\\apps\\\.+\\\.+\\\(.+)\\\.+$/U','$1',$class))
		    )
		);

		$this->__head=(object)array_merge((array)$this->__head,
		  array
		  (
		    'readme'    =>  sysvar::get('apps')."/{$this->__head->app}/{$this->__head->channel}/{$this->__head->version->organic}/README.txt",
		    'manifest'  =>  sysvar::get('apps')."/{$this->__head->app}/{$this->__head->channel}/{$this->__head->version->organic}/manifest.xml"
		  )
		);

		$x=new \DOMDocument;
		
		$x->load($this->__head->manifest);
		
		$this->__head->dependencies=array();
		
		foreach($x->getElementsByTagName('dependency') as $d)
		
		{
		  $dep=new \stdClass;
		  
		  foreach($d->attributes as $attr)
		  $dep->{$attr->nodeName}=$attr->nodeValue;
		  
		  $this->__head->dependencies[]=$dep;
		}
		
		$this->__head->methods=new \stdClass;
		
		foreach($x->getElementsByTagName('method') as $m)
		$this->__head->methods->{$m->getAttribute('for')}=$m->firstChild->nodeValue;
	}
	
	public function
	__call
	(
		$function,
		$arguments
	)
	{
    foreach($this->__head->methods as $meth=>$regex)
    if(preg_match($regex,$function))
    $function=$meth;
	  
		return call_user_func_array(array(new \ReflectionClass(preg_replace('/\\\run$/','',get_class($this))."\\$function"),'newInstanceArgs'),array($arguments));
	}
	
	public function
	__invoke
	(
	  $arg=null
	)
	{
	  switch(true)
	  
	  {
	    case is_null($arg):
	    
	      if(is_readable($this->__head->readme))
        return trim(file_get_contents($this->__head->readme));
        
        quit(ES_NO_README,'No ReadMe found for this app version');
	    
	    break;
	    
	    case $arg=='FILE':
	    
	      return $this->__head->readme;
	    
	    break;
	  }
	}
}
